package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.truck;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CIcCardsInfoMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CTrucksMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Component
public class TruckQueueZxBu {
    @Autowired
    private ISysDicService sysDicService;
    //    CTrucksUpdate的service
    @Autowired
    private ICTrucksUpdateService cTrucksUpdateService;
    //    CTrucks的service
    @Autowired
    private ICTrucksService cTrucksService;
    @Autowired
    private ICProductsInfoService cProductsInfoService;
    @Autowired
    private ICIcCardsAuthService cIcCardsAuthService;
    @Autowired
    private ICIcCardsInfoService cIcCardsInfoService;
    @Autowired
    private ICCompanysService cCompanysService;
    @Autowired
    private CIcCardsInfoMapper cIcCardsInfoMapper;
    @Autowired
    private QueueHandlingBu queueHandlingBu;
    @Autowired
    private QueueHandlingZxBu queueHandlingZxBu;
    @Autowired
    private ICPdtClassService cPdtClassService;
    @Autowired
    private ITSpecialPriceTypeService itSpecialPriceTypeService;
    @Autowired
    private ITSpecialPriceService itSpecialPriceService;
    @Autowired
    private ITTruckBlacklistService iTTruckBlacklistService;
    @Autowired
    private ITTrucksOvertimeService iTTrucksOvertimeService;
    @Autowired
    private ICSysCfgService cSysCfgService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ICOrderDetailService iCOrderDetailService;
    @Autowired
    private CTrucksMapper cTrucksMapper;
    @Autowired
    private UserInfoDao  userInfoDao;
    @Autowired
    private ITGypsumPlanService iTGypsumPlanService;
    public Map<String, Object> startQueueByTruckNoZx(String token, String cardinfCompany, String cardinfTruckTypeValue, String cardinfTruckPwd , String plantId) throws Exception {
//排队时间
        LocalDateTime now = LocalDateTime.now();
        CCompanys cCompanys1 = null;
if (!cardinfCompany.contains(".")) {
     cCompanys1 = cCompanysService.getById(cardinfCompany);
}else {
//   根据.分割
    String[] split = cardinfCompany.split("\\.");
    String co = split[0];
    String chiCo = split[1];
    QueryWrapper<CCompanys> cCompanysQueryWrapper = new QueryWrapper<>();
    cCompanysQueryWrapper.eq("CPY_CO", co);
    cCompanysQueryWrapper.eq("CPY_CHICO", chiCo);
    cCompanysQueryWrapper.eq("CPY_DELETED", 0);
    cCompanysQueryWrapper.eq("DATA_FROM", plantId);
    cCompanys1 = cCompanysService.getOne(cCompanysQueryWrapper);
}
        Map<String, Object> map1 = new HashMap<>();
//        QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper5 = new QueryWrapper<>();
//        cTrucksUpdateQueryWrapper5.eq("TRUCKS_DELETED", 0);
//        cTrucksUpdateQueryWrapper5.eq("UPDATE_TYPE", 5);
//        cTrucksUpdateQueryWrapper5.eq("TRUCKS_NEW", 1);
//        cTrucksUpdateQueryWrapper5.ge("HANDLED_TIME", now.truncatedTo(ChronoUnit.MINUTES).minusMinutes(5)); // 确保查询范围是最近2分钟
//        cTrucksUpdateQueryWrapper5.orderByDesc("HANDLED_TIME");
//        List<CTrucksUpdate> cTrucksUpdate5 = cTrucksUpdateService.list(cTrucksUpdateQueryWrapper5);
//        if (cTrucksUpdate5.size() >= 5) {
//            map1.put("code", 1);
//            map1.put("msg", "当前排队车辆过多，请过5分钟后再排队");
//            return map1;
//        }
//        查询品种id
        QueryWrapper<CProductsInfo> productsInfoWrapper = new QueryWrapper<>();
        productsInfoWrapper.eq("PDTINF_PDT", cardinfTruckTypeValue);
        productsInfoWrapper.eq("PDTINF_DELETED", 0);
        CProductsInfo productsInfo = cProductsInfoService.getOne(productsInfoWrapper);
//        所属电厂
        SysUser user =  null;
        if (token !=null) {
             user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        }
        String plant = plantId;


        //        判断车辆已经超时几次了
        QueryWrapper<CTrucks> cTrucksQueryWrapper6 = new QueryWrapper<>();
        cTrucksQueryWrapper6.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
        cTrucksQueryWrapper6.eq("TRUCKS_DELETED", 0);
//    HANDLED的值为字符串******，里面存在0，就说明还没处理
        CTrucks cTrucks6 = cTrucksService.getOne(cTrucksQueryWrapper6);
        if (cTrucks6 != null) {
//            查下车辆是否批准了
            if (cTrucks6.getTrucksInfoApproved() != null && cTrucks6.getTrucksInfoApproved() == 0) {
                map1.put("code", 1);
                map1.put("msg", "该车辆未批准");
                return map1;
            }
            int count = getOverTimeCount( cTrucks6.getId(), now);
//          查询配置表要几次再拉黑
            QueryWrapper<SysDic> sysDic = new QueryWrapper<>();
            sysDic.eq("DIC_KEY", "queue_truck_overtime_count");
            sysDic.eq("DATA_FROM", plant);
            SysDic sysDic1 = sysDicService.getOne(sysDic);
            if (count >= Integer.parseInt(sysDic1.getDicVal())) {
                // Get the start of the current day (midnight)
                LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);

                // Check if the truck is already blacklisted for the current day
                QueryWrapper<TTruckBlacklist> blacklistQueryWrapper = new QueryWrapper<>();
                blacklistQueryWrapper.eq("TRUCK_ID", cTrucks6.getId());
                blacklistQueryWrapper.ge("END_TIME", startOfDay);  // Get only blacklists that are still active for the current day
                List<TTruckBlacklist> existingBlacklist = iTTruckBlacklistService.list(blacklistQueryWrapper);
                if (existingBlacklist.size()==0) {
                    // The truck is not currently blacklisted, so proceed to blacklist it
                    // Query the number of days to blacklist
                    QueryWrapper<SysDic> sysDicQueryWrapper = new QueryWrapper<>();
                    sysDicQueryWrapper.eq("DIC_KEY", "queue_truck_blacklist_days");
                    sysDicQueryWrapper.eq("DATA_FROM", plant);
                    SysDic sysDic2 = sysDicService.getOne(sysDicQueryWrapper);
                    int days = Integer.parseInt(sysDic2.getDicVal());
                    LocalDateTime plusDays = now.plusDays(days);
                    TTruckBlacklist iTTruckBlacklist = new TTruckBlacklist();
                    iTTruckBlacklist.setTruckId(cTrucks6.getId());
                    iTTruckBlacklist.setStartTime(now);
                    iTTruckBlacklist.setEndTime(plusDays);
                    iTTruckBlacklist.setTruckNo(cTrucks6.getTrucksTruckno());
                    iTTruckBlacklist.setRemark("因多次叫号超时由系统自动拉黑");
                    iTTruckBlacklistService.save(iTTruckBlacklist);
                    map1.put("code", 1);
                    map1.put("msg", "该车正在黑名单中");
                    return map1;
                }
            }
        }
//判断车辆的黑名单
        if (cTrucks6 != null) {
            if (getBlackList( cTrucks6.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "该车正在黑名单中");
                return map1;
            }
        }
//        String cardinfTruckTypeValue = map.get("cardinfTruckTypeValue").toString();
//        排队卡号 cardauthCardno

//        排队车号 cardinfTruckPwd
//        String cardinfTruckPwd = map.get("cardinfTruckPwd").toString();
//        查询这个车号的代理卡
        List<CIcCardsInfo> cIcCardsInfos = cIcCardsInfoMapper.selectIcAgentByTruckNo(plant, cardinfTruckPwd);
        String cardauthCardno = null;
        if (cIcCardsInfos.size()>0) {
            cardauthCardno = cIcCardsInfos.get(0).getCardinfCardno();
        }
//        else if (cIcCardsInfos.size() > 1) {
//            map1.put("code", 1);
//            map1.put("msg", "该车辆有多个代理卡，请联系管理员");
//            return map1;
//        }
        //        排队司机姓名 cardauthDriverUserName
        String cardauthDriverUserName = "";
        if (user !=null && user.getTrueName() != null){
             cardauthDriverUserName = user.getTrueName();
        }
//    司机手机号 cardauthDriverPhone
        String cardauthDriverPhone = "";
        if (user !=null && user.getPhone() != null) {
            cardauthDriverPhone = user.getPhone();
        }
//        收货单位 cardinfCompany
//        String cardinfCompany = map.get("cardinfCompany").toString();
        //cardinfCompany 根据.分割

        String cardinfCompanyCo = cCompanys1.getCpyCo();
        String cardinfCompanyChiCo = cCompanys1.getCpyChico();
        QueryWrapper<CCompanys> cCompanysQueryWrapper = new QueryWrapper<>();
        cCompanysQueryWrapper.eq("CPY_CO", cardinfCompanyCo);
        cCompanysQueryWrapper.eq("CPY_CHICO", cardinfCompanyChiCo);
        cCompanysQueryWrapper.ne("CPY_DELETED", 1);
        cCompanysQueryWrapper.eq("DATA_FROM", plant);
        CCompanys cCompanys = cCompanysService.getOne(cCompanysQueryWrapper);
        String cardinfCompanyId = cCompanys.getId();
        if (cardauthCardno != null) {
            int isOk = cIcCardsInfoMapper.selectCountAgent(plant, cardauthCardno);
            if (isOk == 0) {
                map1.put("code", 1);
                map1.put("msg", "此卡已注销或挂失");
                return map1;
            }
        }
        CTrucks cTrucks = cTrucks6;
//        查询是否开启大袋灰排队
        if (cardinfTruckTypeValue.contains("大袋灰")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_dadaihui");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启大袋灰的排队");
                return map1;
            }
        }
//        查询是否开启加湿灰排队
        if (cardinfTruckTypeValue.contains("加湿灰")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_jiashihui");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启加湿灰的排队");
                return map1;
            }
        }
//        查询是否开启转倒炉渣排队
        if (cardinfTruckTypeValue.contains("转倒炉渣")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_zhuandaoshizha");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启转倒炉渣的排队");
                return map1;
            }
        }
        //        查询是否开启应急炉渣排队
        if (cardinfTruckTypeValue.contains("应急炉渣")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_yingjishizha");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启应急炉渣的排队");
                return map1;
            }
        }
//        判断是否开启其他物资的排队
        if (productsInfo.getPdtinfClass().equals("4")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_otherProduct");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启其他物资的排队");
                return map1;
            }
        }
        //    一二期石膏、三四期石膏这两品种排队要判断有没有打包销售的量
//        public boolean ifPackageSell(String plant, String coId, String pdtId, String checkinTm) {
        if (productsInfo.getId().equals("8bebefb14fe3419ea957591b01774274")) {//一二期石膏
            if ( ifPackageSell( plant,  cardinfCompanyId, productsInfo.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "一二期石膏没有打包销售的量");
                return map1;
            }
        }
        if (productsInfo.getId().equals("3365a55ec72e4e12b1ace84b2fdd9bec")) {//三四期石膏
            if ( ifPackageSell( plant,  cardinfCompanyId, productsInfo.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "三四期石膏没有打包销售的量");
                return map1;
            }
        }
//        这里判断可以使用临时车排队的品种,否则都得判断这个车是否在车库里面
        if (getCanUseTempTruckNo(productsInfo, plant)
        ) {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
            cTrucksQueryWrapper.ne("TRUCKS_DELETED", 1);
            cTrucksQueryWrapper.eq("DATA_FROM", plant);
            cTrucks = cTrucksService.getOne(cTrucksQueryWrapper);
            if (cTrucks == null) {
                map1.put("code", 1);
                map1.put("msg", "车号不在车库中，请联系管理员添加车号");
                return map1;
            }
        }
//       判断是否开启临时车号排队
        QueryWrapper<SysDic> dicqueryWrapper = new QueryWrapper<>();
        dicqueryWrapper.eq("DIC_KEY", "queue_temporary");
        dicqueryWrapper.eq("DATA_FROM", plant);
        SysDic sysDic1 = sysDicService.getOne(dicqueryWrapper);
        if (sysDic1.getDicVal().equals("0")) {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
            cTrucksQueryWrapper.ne("TRUCKS_DELETED", 1);
            cTrucksQueryWrapper.eq("DATA_FROM", plant);
            cTrucks = cTrucksService.getOne(cTrucksQueryWrapper);
            if (cTrucks == null) {
                map1.put("code", 1);
                map1.put("msg", "车号不在车库中，请联系管理员添加车号");
                return map1;
            }
        } else {
//            临时车加入车库
            if (cTrucks == null) {
                try {
                    Map<String, Object> map = addTruck(cardinfTruckPwd, null, "0", null, null, null, null, null, null, null, null, null, user, plant);
                    if (map.get("code").toString().equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", map.get("msg"));
                        return map1;
                    }else{
//                        加成功了就把车子拿出来
                        QueryWrapper<CTrucks> cTrucks1 = new QueryWrapper<>();
                        cTrucks1.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
                        cTrucks1.eq("TRUCKS_DELETED", 0);
                        cTrucks1.eq("DATA_FROM", plant);
                        cTrucks = cTrucksService.getOne(cTrucks1);
                    }
                } catch (Exception e) {
                    map1.put("code", 1);
                    map1.put("msg", "使用临时车排队失败");
                    return map1;
                }
            }
        }
        if (cTrucks != null) {
            try {
                QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper9 = new QueryWrapper<>();
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_DELETED", 0);
                cTrucksUpdateQueryWrapper9.eq("UPDATE_TYPE", 5);
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_NEW", 1);
//            HANDLED_TIME一天之内
                cTrucksUpdateQueryWrapper9.ge("HANDLED_TIME", now.truncatedTo(ChronoUnit.DAYS));
//            根据HANDLED_TIME查到最新的一条
                cTrucksUpdateQueryWrapper9.orderByDesc("HANDLED_TIME");
                cTrucksUpdateQueryWrapper9.last("limit 1");
                CTrucksUpdate cTrucksUpdate9 = cTrucksUpdateService.getOne(cTrucksUpdateQueryWrapper9);
                if (cTrucksUpdate9 != null) {
                    if (!cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆仍在队列中,由用户" + cTrucksUpdate9.getTrucksCheckinDriver() + "-" + cTrucksUpdate9.getTrucksCheckinDriverPhone() + "排队，请等待完成出厂后再申请排队");
                        return map1;
                    }
                } else {
                    if (cTrucks.getTrucksQueueStatus() != null && !cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆仍在队列中,请等待完成出厂后再申请排队");
                        return map1;
                    }
                }
            } catch (Exception e) {
                if (cTrucks.getTrucksQueueStatus() != null && !cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                    map1.put("code", 1);
                    map1.put("msg", "该车辆仍在队列中,请等待完成出厂后再申请排队");
                    return map1;
                }
            }
        }
//        if (productsInfo.getPdtinfSpeSitelist() != null) {
////            当品种有装载点时cardinfTruckName不能为空
//            if (cardinfTruckName == null || cardinfTruckName.equals("")) {
//                map1.put("code", 1);
//                map1.put("msg", "请选择装卸货点!!!");
//                return map1;
//            }
//        }
        //        判断余额
//        queueHandlingBu.balanceIsEnough(plant, cardauthCardno);如果是false就提示余额不足
//        plant=DATA_FROM \ cardauthCardno=卡号 、cardinfTruckTypeValue=品种名称 、 cardinfTruckPwd=车号
//        if (!queueHandlingZxBu.balanceIsEnough(plant,cardinfCompanyCo,cardinfCompanyChiCo, cardinfTruckTypeValue, cardinfTruckPwd)) {
//            map1.put("code", 1);
//            map1.put("msg", "排队单位余额不足，请充值");
//            return map1;
//        }
//       邹县只判断下限余量
        Map<String, Object> isLowerLimit = queueHandlingZxBu.isLowerLimit(plant, cardinfCompanyCo, cardinfCompanyChiCo, cardinfTruckTypeValue);
        if (!isLowerLimit.get("ok").equals("0.0")) {
            map1.put("code", 1);
            if (!isLowerLimit.get("SubjectName").toString().equals("")) {
                map1.put("msg", "排队单位的【" + isLowerLimit.get("SubjectName").toString() + "】账户余额不足装" + isLowerLimit.get("limit").toString() + "吨");
            } else {
                map1.put("msg", "排队单位未创建余额账户");
            }
            return map1;
        }
//        邹县判断电厂公司余额下限  Map<String> getDianchangOrGongsiRemainMap = getDianchangOrGongsiRemain();
        Map<String, Object> isLowerLimit1 = getDianchangOrGongsiRemain(cCompanys.getId(), plant);
        if (Integer.parseInt(isLowerLimit1.get("code").toString()) == 1) {
            map1.put("code", 1);
            map1.put("msg", isLowerLimit1.get("msg"));
            return map1;
        }
//        判断是否还有计划
        boolean isPlan = queueHandlingZxBu.isPlan(plant, cardinfCompanyCo, cardinfCompanyChiCo, cardinfTruckTypeValue, cardinfTruckPwd);
        if (!isPlan) {
            map1.put("code", 1);
            map1.put("msg", "无计划或计划已用完了");
            return map1;
        }

//        判断石膏渣是否有计划
//        这里还要排队石膏渣里有没有不需要排计划的品种
        if (getNoNeedPlan(productsInfo, plant)) {
//            只判断石膏和储备库炉渣的计划
            if (productsInfo.getPdtinfClass().equals("2") || productsInfo.getId().equals("c9cf42874ddc446891ec936c5bf67386")) {
                String pdtId = productsInfo.getId();
                String supplyCoId = null;
                //如果是一二期石膏或者三四期石膏，就根据当天计划是公司最多还是电厂最多那个算
                if (productsInfo.getId().equals("8bebefb14fe3419ea957591b01774274") || productsInfo.getId().equals("3365a55ec72e4e12b1ace84b2fdd9bec")) {
                    supplyCoId = (String) queueHandlingZxBu.getTodayPlan(now);
                    if (supplyCoId == null) {
                        map1.put("code", 1);
                        map1.put("msg", "没有计划");
                        return map1;
                    }
                }
//                否则就是石膏本身或者其他石膏品种，必须严格按照计划执行
                else {
                    Map<String, Object> isPlan1 = queueHandlingZxBu.isPlan2(cCompanys1.getId(), pdtId);
                    if (isPlan1.get("code").equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", "没有计划");
                        return map1;
                    }
                    TGypsumPlan gypsumPlan = (TGypsumPlan) isPlan1.get("gypsumPlan");
                    supplyCoId = gypsumPlan.getSupplyCoId();

                }
                if (supplyCoId == null){
                    map1.put("code", 1);
                    map1.put("msg", "没有计划");
                    return map1;
                }
                UpdateWrapper<CTrucks> cTrucksUpdateWrapper = new UpdateWrapper<>();
                cTrucksUpdateWrapper.eq("ID", cTrucks.getId());
                cTrucksUpdateWrapper.set("SUPPLY_CO_ID", supplyCoId);
                cTrucksService.update(cTrucksUpdateWrapper);
            }
        }
//        =============================至此开始排队==================================================
        //        判断公司、电厂只要有一余额小于下限余额的就不给排队

//        查询管理员是否开启手机排队
        QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DIC_TYPE", "queue_phone");
        queryWrapper.eq("DIC_KEY", "queueControl");
        queryWrapper.eq("DATA_FROM", plant);
//        拿到结果
        SysDic sysDic = sysDicService.getOne(queryWrapper);
//        如果结果值为0，说明管理员开启了手机排队
//        if (sysDic.getDicVal().equals("0")) {
//            找到ic卡的授权信息
            QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper = new QueryWrapper<>();
            cTrucksUpdateQueryWrapper.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
            cTrucksUpdateQueryWrapper.eq("TRUCKS_DELETED", 0);
            cTrucksUpdateQueryWrapper.eq("TRUCKS_NEW", 1);
//    HANDLED的值为字符串******，里面存在0，就说明还没处理
            cTrucksUpdateQueryWrapper.like("HANDLED", "0");
            CTrucksUpdate cTrucksUpdate1 = cTrucksUpdateService.getOne(cTrucksUpdateQueryWrapper);
            if (cTrucksUpdate1 != null) {
                String[] split = cTrucksUpdate1.getHandled().split("");
                for (String s : split) {
                    if (s.equals("0") || s.equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆排队申请中，申请人:" + cTrucksUpdate1.getTrucksCheckinDriver() + "-" + cTrucksUpdate1.getTrucksCheckinDriverPhone() + "，请勿重复申请排队");
                        return map1;
                    }
                }
            }
            //        写入排队信息
            CTrucksUpdate cTrucksUpdate = new CTrucksUpdate();
            if (cTrucks != null) {
                cTrucksUpdate.setTrucksId(cTrucks.getTrucksId());
            }
            cTrucksUpdate.setTrucksTruckno(cardinfTruckPwd);
            cTrucksUpdate.setTrucksCheckinCo(cardinfCompanyId);
            cTrucksUpdate.setTrucksCheckinPdt(productsInfo.getId());
            cTrucksUpdate.setTrucksCheckinPdtsn(productsInfo.getPdtinfSn());
        if (cardauthCardno != null) {
            cTrucksUpdate.setTrucksCheckinCardno(cardauthCardno);
        } else if (getTempTruckIc(plant) != null && !cardinfTruckTypeValue.equals("应急加湿灰") && !cardinfTruckTypeValue.equals("加湿灰") && !cardinfTruckTypeValue.equals("转倒加湿灰")
        ) {
            cTrucksUpdate.setTrucksCheckinCardno(getTempTruckIc(plant));
            cardauthCardno = getTempTruckIc(plant);
        } else if ( cardinfTruckTypeValue.equals("加湿灰") || cardinfTruckTypeValue.equals("应急加湿灰") || cardinfTruckTypeValue.equals("转倒加湿灰")) {
            if (cardinfTruckTypeValue.equals("加湿灰")) {
                cardauthCardno = getJiashihuiTempTruckIc(plant, true);
            }else if (cardinfTruckTypeValue.equals("应急加湿灰")) {
                cardauthCardno = getJiashihuiTempTruckIc2(plant, false);
            }else if (cardinfTruckTypeValue.equals("转倒加湿灰")) {
                cardauthCardno = getJiashihuiTempTruckIc3(plant, false);
            }
            if (cardauthCardno !=null) {
                cTrucksUpdate.setTrucksCheckinCardno(cardauthCardno);
            }else {
                map1.put("code", 1);
                map1.put("msg", "暂时无临时卡号可用");
                return map1;
            }
        } else {
            map1.put("code", 1);
            map1.put("msg", "暂时无临时卡号可用");
            return map1;
        }
//                    cTrucksUpdate.setTrucksCheckinLoadsite(cardinfTruckName);
            cTrucksUpdate.setTrucksCheckinDriver(cardauthDriverUserName);
            cTrucksUpdate.setTrucksCheckinDriverPhone(cardauthDriverPhone);
            cTrucksUpdate.setTrucksQueueStatus(BigDecimal.valueOf(0));
            cTrucksUpdate.setHandled5Time(LocalDateTime.now());
            cTrucksUpdate.setHandledTime(LocalDateTime.now());
            cTrucksUpdate.setTrucksDeleted(0);

            cTrucksUpdate.setTrucksNew(1);
            cTrucksUpdate.setUpdateType(5);
//                                    cTrucksUpdate.setUpdateNew(0);
            cTrucksUpdate.setHandledResult(0);
            cTrucksUpdate.setHandled("22220222");
            cTrucksUpdate.setDataFrom(plant);
            cTrucksUpdateService.save(cTrucksUpdate);
            //      存完拿到id
            String id = cTrucksUpdate.getId();
            //                    往trucks表找到这个车号更新一下，往serialno也写入这个id
            QueryWrapper<CTrucks> cTrucksQueryWrapper2 = new QueryWrapper<>();
            cTrucksQueryWrapper2.eq("TRUCKS_TRUCKNO", cardinfTruckPwd);
            cTrucksQueryWrapper2.eq("TRUCKS_DELETED", 0);
            CTrucks cTrucks2 = cTrucksService.getOne(cTrucksQueryWrapper2);
            if (cTrucks2 != null) {
                cTrucks2.setSerialNo(id);
                cTrucksService.updateById(cTrucks2);
            } else {
                map1.put("code", 1);
                map1.put("msg", "系统车库内没有该车号,请联系管理员添加");
                return map1;
            }
            //                    排队成功就将之前的记录置为0，也就是变成历史记录
            QueryWrapper<CTrucksUpdate> queryWrapper7 = new QueryWrapper<>();
            queryWrapper7.eq("ID", cTrucks.getId());
            queryWrapper7.eq("TRUCKS_NEW", 1);
            queryWrapper7.orderByDesc("HANDLED_TIME");
            List<CTrucksUpdate> cTrucksUpdates1 = cTrucksUpdateService.list(queryWrapper7);
            if (!cTrucksUpdates1.isEmpty()) {
                for (int i = 1; i < cTrucksUpdates1.size(); i++) {
                    CTrucksUpdate cTrucksUpdate2 = cTrucksUpdates1.get(i);
                    cTrucksUpdate2.setTrucksNew(0);
                    cTrucksUpdateService.updateById(cTrucksUpdate2);
                }
            }
//            先初始化特权
        cTrucks.setTrucksQueueVip(0);
//            车辆是否有vip排队特权
            if (cTrucks6 != null && cTrucks6.getTrucksQueueVipNums() > 0) {
                cTrucks.setTrucksQueueVipNums(cTrucks6.getTrucksQueueVipNums() - 1);
                cTrucks.setTrucksQueueVip(1);
            }
//            单位是否有vip排队特权
            if (cCompanys.getCpyQueueVip() == 1){
                cTrucks.setTrucksQueueVip(1);
            }
//                    排上队了就先改车子的状态为1
            cTrucks.setTrucksQueueStatus(BigDecimal.valueOf(1));
            //                进门是0
            cTrucks.setTrucksEntered(0);
            cTrucks.setTrucksEnterTm(null);
            cTrucks.setTrucksCheckinLoadsiteAdd("");
           cTrucks.setTrucksCheckinCardno(cardauthCardno);
            cTrucks.setTrucksCheckinCo(cardinfCompanyId);
            cTrucks.setTrucksCheckinPdt(productsInfo.getId());
            cTrucks.setTrucksCheckinTm(now);
            cTrucksService.updateById(cTrucks);
            //    直接叫号的品种，这些品种都是由装载点带回装载点编号，然后扣款时要根据装载点去找到是扣公司还是电厂的余额
            if (productsInfo.getId().equals("56260577b0ab4b5d9b84d9577fcac1d0")//大袋灰
                    || productsInfo.getId().equals("1dce738280ff4cfc946659990c8a05b6")//钢板仓粗灰
                    || productsInfo.getId().equals("025c559037d7462383b053630239ee49")//钢板仓原灰
//                    || productsInfo.getId().equals("8bebefb14fe3419ea957591b01774274")//一二期石膏
//                    || productsInfo.getId().equals("3365a55ec72e4e12b1ace84b2fdd9bec")//三四期石膏
//                    || productsInfo.getId().equals("7472d52542c54ce78917781471497559")//石膏
//                    || productsInfo.getId().equals("c9cf42874ddc446891ec936c5bf67386")//储备库炉渣
                    || productsInfo.getId().equals("af09ebfbecc04a4487f391f38567d8a8")//#6炉炉渣
                    || productsInfo.getId().equals("6225c8276b9e405a9bc61c1bc2d651cc")//#4炉炉渣
                    || productsInfo.getPdtinfClass().equals("4")//所有其他物资
                    || productsInfo.getId().equals("02fadd3e453840a5a19ee50d95a0092a")//转倒加湿灰
                    || productsInfo.getId().equals("f725ab248ca64e0ba3d3612eb0dab882")//应急加湿灰
                    || productsInfo.getId().equals("eaf0abcd61c04613aaa0d2387fee8fb6")//应急炉渣
                    || productsInfo.getId().equals("3cdf25f724764feea4d0d277667a2607")//转倒炉渣
                    || productsInfo.getId().equals("b9da511ff1dd4969a0e9ce0dbeeb91c9")//加湿灰
            ) {
                cTrucks.setTrucksCheckinLoadsite("");
                cTrucksService.updateById(cTrucks);
            }
//            cTrucks.setTrucksCheckinLoadsite(null);
//            cTrucks.setPriceType(null);
            UpdateWrapper<CTrucks> cTrucksUpdateWrapper = new UpdateWrapper<>();
            cTrucksUpdateWrapper.eq("ID", cTrucks.getId());
            cTrucksUpdateWrapper.set("TRUCKS_CHECKIN_LOADSITE",null);
            cTrucksUpdateWrapper.set("TRUCKS_CALLIN_TM",null);
            cTrucksUpdateWrapper.set("PRICE_TYPE", null);
            cTrucksUpdateWrapper.set("PRICE_ID", null);
            cTrucksUpdateWrapper.set("SPECIAL_PRICE", null);
            cTrucksService.update(cTrucksUpdateWrapper);
            //                    直接扣掉他的定价剩余情况
            TSpecialPrice priceDetail = getPriceDetail(productsInfo.getId(), cardinfCompanyId, String.valueOf(LocalDateTime.now()));
            if (priceDetail != null) {
                TSpecialPrice tSpecialPrice = new TSpecialPrice();
                tSpecialPrice.setId(priceDetail.getId());
                tSpecialPrice.setResidueNum(priceDetail.getResidueNum().subtract(BigDecimal.valueOf(1)));
                itSpecialPriceService.updateById(tSpecialPrice);
//                cTrucks.setSpecialPrice(tSpecialPrice.getPrice());
//                cTrucks.setPriceType(tSpecialPrice.getPriceType());
//                cTrucks.setPriceId(tSpecialPrice.getPriceTypeId());
//                UpdateWrapper<CTrucks> cTrucksUpdateWrapper1 = new UpdateWrapper<>();
//                cTrucksUpdateWrapper1.eq("ID", cTrucks.getId());
//                cTrucksUpdateWrapper1.set("PRICE_TYPE", tSpecialPrice.getPriceType());
//                cTrucksUpdateWrapper1.set("SPECIAL_PRICE", tSpecialPrice.getPrice());
//                cTrucksUpdateWrapper1.set("PRICE_ID", tSpecialPrice.getPriceTypeId());
//                cTrucksService.update(cTrucksUpdateWrapper1);
                cTrucks.setId(cTrucks.getId());
                cTrucks.setSpecialPrice(priceDetail.getPrice());
                cTrucks.setPriceType(priceDetail.getPriceType());
                cTrucks.setPriceId(priceDetail.getPriceTypeId());
                cTrucksService.updateById(cTrucks);
            }else {
//                cTrucks.setSpecialPrice(null);
//                cTrucks.setPriceType(null);
//                cTrucks.setPriceId(null);
                UpdateWrapper<CTrucks> cTrucksUpdateWrapper1 = new UpdateWrapper<>();
                cTrucksUpdateWrapper1.eq("ID", cTrucks.getId());
                cTrucksUpdateWrapper1.set("PRICE_TYPE", "市场价");
                cTrucksUpdateWrapper1.set("SPECIAL_PRICE", BigDecimal.valueOf(0));
                cTrucksUpdateWrapper1.set("PRICE_ID", "100db760390111ef987900ff8a757bed");
                cTrucksService.update(cTrucksUpdateWrapper1);
            }
            //            返回结果
            map1.put("id", id);
            map1.put("code", 0);
            map1.put("msg", "申请排队成功，请等待服务器响应");
            return map1;
//        } else {
////            管理员关闭了手机排队往Map里写入错误信息
//            map1.put("code", 1);
//            map1.put("msg", "管理员关闭了手机排队功能");
//            return map1;
//        }
    }
//本地排队机接口
    public Map<String, Object> startQueueByTruckNoZxLocal(String token, String cardinfCompany, String cardinfTruckTypeValue, String cardinfTruckPwd , String plantId) throws Exception {
//排队时间
        LocalDateTime now = LocalDateTime.now();
        CCompanys cCompanys1 = null;
            cCompanys1 = cCompanysService.getById(cardinfCompany);

        Map<String, Object> map1 = new HashMap<>();
//        QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper5 = new QueryWrapper<>();
//        cTrucksUpdateQueryWrapper5.eq("TRUCKS_DELETED", 0);
//        cTrucksUpdateQueryWrapper5.eq("UPDATE_TYPE", 5);
//        cTrucksUpdateQueryWrapper5.eq("TRUCKS_NEW", 1);
//        cTrucksUpdateQueryWrapper5.ge("HANDLED_TIME", now.truncatedTo(ChronoUnit.MINUTES).minusMinutes(5)); // 确保查询范围是最近2分钟
//        cTrucksUpdateQueryWrapper5.orderByDesc("HANDLED_TIME");
//        List<CTrucksUpdate> cTrucksUpdate5 = cTrucksUpdateService.list(cTrucksUpdateQueryWrapper5);
//        if (cTrucksUpdate5.size() >= 5) {
//            map1.put("code", 1);
//            map1.put("msg", "当前排队车辆过多，请过5分钟后再排队");
//            return map1;
//        }
//        查询品种id
        QueryWrapper<CProductsInfo> productsInfoWrapper = new QueryWrapper<>();
        productsInfoWrapper.eq("ID", cardinfTruckTypeValue);
        CProductsInfo productsInfo = cProductsInfoService.getOne(productsInfoWrapper);
//        所属电厂
        SysUser user =  null;
        if (token !=null) {
            user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        }
        String plant = plantId;


        //        判断车辆已经超时几次了
        QueryWrapper<CTrucks> cTrucksQueryWrapper6 = new QueryWrapper<>();
        cTrucksQueryWrapper6.eq("ID", cardinfTruckPwd);
//    HANDLED的值为字符串******，里面存在0，就说明还没处理
        CTrucks cTrucks6 = cTrucksService.getOne(cTrucksQueryWrapper6);
        if (cTrucks6 != null) {
//            查下车辆是否批准了
            if (cTrucks6.getTrucksInfoApproved() != null && cTrucks6.getTrucksInfoApproved() == 0) {
                map1.put("code", 1);
                map1.put("msg", "该车辆未批准");
                return map1;
            }
            int count = getOverTimeCount( cTrucks6.getId(), now);
//          查询配置表要几次再拉黑
            QueryWrapper<SysDic> sysDic = new QueryWrapper<>();
            sysDic.eq("DIC_KEY", "queue_truck_overtime_count");
            sysDic.eq("DATA_FROM", plant);
            SysDic sysDic1 = sysDicService.getOne(sysDic);
            if (count >= Integer.parseInt(sysDic1.getDicVal())) {
                // Get the start of the current day (midnight)
                LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);

                // Check if the truck is already blacklisted for the current day
                QueryWrapper<TTruckBlacklist> blacklistQueryWrapper = new QueryWrapper<>();
                blacklistQueryWrapper.eq("TRUCK_ID", cTrucks6.getId());
                blacklistQueryWrapper.ge("END_TIME", startOfDay);  // Get only blacklists that are still active for the current day
                List<TTruckBlacklist> existingBlacklist = iTTruckBlacklistService.list(blacklistQueryWrapper);
                if (existingBlacklist.size()==0) {
                    // The truck is not currently blacklisted, so proceed to blacklist it
                    // Query the number of days to blacklist
                    QueryWrapper<SysDic> sysDicQueryWrapper = new QueryWrapper<>();
                    sysDicQueryWrapper.eq("DIC_KEY", "queue_truck_blacklist_days");
                    sysDicQueryWrapper.eq("DATA_FROM", plant);
                    SysDic sysDic2 = sysDicService.getOne(sysDicQueryWrapper);
                    int days = Integer.parseInt(sysDic2.getDicVal());
                    LocalDateTime plusDays = now.plusDays(days);
                    TTruckBlacklist iTTruckBlacklist = new TTruckBlacklist();
                    iTTruckBlacklist.setTruckId(cTrucks6.getId());
                    iTTruckBlacklist.setStartTime(now);
                    iTTruckBlacklist.setEndTime(plusDays);
                    iTTruckBlacklist.setTruckNo(cTrucks6.getTrucksTruckno());
                    iTTruckBlacklist.setRemark("因多次叫号超时由系统自动拉黑");
                    iTTruckBlacklistService.save(iTTruckBlacklist);
                    map1.put("code", 1);
                    map1.put("msg", "该车正在黑名单中");
                    return map1;
                }
            }
        }else {
            map1.put("code", 1);
            map1.put("msg", "该车辆不存在");
            return map1;
        }
//判断车辆的黑名单
        if (cTrucks6 != null) {
            if (getBlackList( cTrucks6.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "该车正在黑名单中");
                return map1;
            }
        }
//        String cardinfTruckTypeValue = map.get("cardinfTruckTypeValue").toString();
//        排队卡号 cardauthCardno

//        排队车号 cardinfTruckPwd
//        String cardinfTruckPwd = map.get("cardinfTruckPwd").toString();
//        查询这个车号的代理卡
        List<CIcCardsInfo> cIcCardsInfos = null;
        if (cTrucks6 != null) {
            cIcCardsInfos = cIcCardsInfoMapper.selectIcAgentByTruckNoById(plant, cTrucks6.getTrucksTruckno());
        }
        String cardauthCardno = "";
        if (cIcCardsInfos.size() == 1) {
            cardauthCardno = cIcCardsInfos.get(0).getCardinfCardno();
        } else if (cIcCardsInfos.size() > 1) {
            map1.put("code", 1);
            map1.put("msg", "该车辆有多个代理卡，请联系管理员");
            return map1;
        }
        //        排队司机姓名 cardauthDriverUserName
        String cardauthDriverUserName = "";
        if (user !=null && user.getTrueName() != null){
            cardauthDriverUserName = user.getTrueName();
        }
//    司机手机号 cardauthDriverPhone
        String cardauthDriverPhone = "";
        if (user !=null && user.getPhone() != null) {
            cardauthDriverPhone = user.getPhone();
        }
//        收货单位 cardinfCompany
//        String cardinfCompany = map.get("cardinfCompany").toString();
        //cardinfCompany 根据.分割

        String cardinfCompanyCo = cCompanys1.getCpyCo();
        String cardinfCompanyChiCo = cCompanys1.getCpyChico();
        QueryWrapper<CCompanys> cCompanysQueryWrapper = new QueryWrapper<>();
        cCompanysQueryWrapper.eq("CPY_CO", cardinfCompanyCo);
        cCompanysQueryWrapper.eq("CPY_CHICO", cardinfCompanyChiCo);
        cCompanysQueryWrapper.ne("CPY_DELETED", 1);
        cCompanysQueryWrapper.eq("DATA_FROM", plant);
        CCompanys cCompanys = cCompanysService.getOne(cCompanysQueryWrapper);
        String cardinfCompanyId = cCompanys.getId();
        if (cardauthCardno != null) {
            int isOk = cIcCardsInfoMapper.selectCountAgent(plant, cardauthCardno);
            if (isOk == 0) {
                map1.put("code", 1);
                map1.put("msg", "此卡已注销或挂失");
                return map1;
            }
        }
        CTrucks cTrucks = cTrucks6;
//        查询是否开启大袋灰排队
        if (cardinfTruckTypeValue.contains("56260577b0ab4b5d9b84d9577fcac1d0")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_dadaihui");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启大袋灰的排队");
                return map1;
            }
        }
//        查询是否开启加湿灰排队
        if (cardinfTruckTypeValue.contains("b9da511ff1dd4969a0e9ce0dbeeb91c9")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_jiashihui");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启加湿灰的排队");
                return map1;
            }
        }
//        查询是否开启转倒炉渣排队
        if (cardinfTruckTypeValue.contains("3cdf25f724764feea4d0d277667a2607")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_zhuandaoshizha");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启转倒炉渣的排队");
                return map1;
            }
        }
        //        查询是否开启应急炉渣排队
        if (cardinfTruckTypeValue.contains("eaf0abcd61c04613aaa0d2387fee8fb6")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_yingjishizha");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启应急炉渣的排队");
                return map1;
            }
        }
//        判断是否开启其他物资的排队
        if (productsInfo.getPdtinfClass().equals("4")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queue_otherProduct");
            queryWrapper.eq("DATA_FROM", plant);
            SysDic sysDic = sysDicService.getOne(queryWrapper);
            if (sysDic.getDicVal().equals("0")) {
                map1.put("code", 1);
                map1.put("msg", "未开启其他物资的排队");
                return map1;
            }
        }
        //    一二期石膏、三四期石膏这两品种排队要判断有没有打包销售的量
//        public boolean ifPackageSell(String plant, String coId, String pdtId, String checkinTm) {
        if (cardinfTruckTypeValue.equals("8bebefb14fe3419ea957591b01774274")) {
            if ( ifPackageSell( plant,  cardinfCompanyId, productsInfo.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "一二期石膏没有打包销售的量");
                return map1;
            }
        }
        if (cardinfTruckTypeValue.equals("3365a55ec72e4e12b1ace84b2fdd9bec")) {
            if ( ifPackageSell( plant,  cardinfCompanyId, productsInfo.getId(), now)) {
                map1.put("code", 1);
                map1.put("msg", "三四期石膏没有打包销售的量");
                return map1;
            }
        }
//        这里判断可以使用临时车排队的品种,否则都得判断这个车是否在车库里面
        if (getCanUseTempTruckNo(productsInfo, plant)
        ) {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("ID", cardinfTruckPwd);
            cTrucksQueryWrapper.ne("TRUCKS_DELETED", 1);
            cTrucksQueryWrapper.eq("DATA_FROM", plant);
            cTrucks = cTrucksService.getOne(cTrucksQueryWrapper);
            if (cTrucks == null) {
                map1.put("code", 1);
                map1.put("msg", "车号不在车库中，请联系管理员添加车号");
                return map1;
            }
        }
//       判断是否开启临时车号排队
        QueryWrapper<SysDic> dicqueryWrapper = new QueryWrapper<>();
        dicqueryWrapper.eq("DIC_KEY", "queue_temporary");
        dicqueryWrapper.eq("DATA_FROM", plant);
        SysDic sysDic1 = sysDicService.getOne(dicqueryWrapper);
        if (sysDic1.getDicVal().equals("0")) {
            QueryWrapper<CTrucks> cTrucksQueryWrapper = new QueryWrapper<>();
            cTrucksQueryWrapper.eq("ID", cardinfTruckPwd);
            cTrucksQueryWrapper.ne("TRUCKS_DELETED", 1);
            cTrucksQueryWrapper.eq("DATA_FROM", plant);
            cTrucks = cTrucksService.getOne(cTrucksQueryWrapper);
            if (cTrucks == null) {
                map1.put("code", 1);
                map1.put("msg", "车号不在车库中，请联系管理员添加车号");
                return map1;
            }
        } else {
////            临时车加入车库
//            if (cTrucks == null) {
//                try {
//
//                    Map<String, Object> map = addTruck(cardinfTruckPwd, null, "0", null, null, null, null, null, null, null, null, null, user, plant);
//                    if (map.get("code").toString().equals("1")) {
//                        map1.put("code", 1);
//                        map1.put("msg", map.get("msg"));
//                        return map1;
//                    }else{
////                        加成功了就把车子拿出来
//                        QueryWrapper<CTrucks> cTrucks1 = new QueryWrapper<>();
//                        cTrucks1.eq("ID", cardinfTruckPwd);
//                        cTrucks1.eq("TRUCKS_DELETED", 0);
//                        cTrucks1.eq("DATA_FROM", plant);
//                        cTrucks = cTrucksService.getOne(cTrucks1);
//                    }
//                } catch (Exception e) {
//                    map1.put("code", 1);
//                    map1.put("msg", "使用临时车排队失败");
//                    return map1;
//                }
//            }
        }
        if (cTrucks != null) {
            try {
                QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper9 = new QueryWrapper<>();
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_TRUCKNO", cTrucks.getTrucksTruckno());
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_DELETED", 0);
                cTrucksUpdateQueryWrapper9.eq("UPDATE_TYPE", 5);
                cTrucksUpdateQueryWrapper9.eq("TRUCKS_NEW", 1);
//            HANDLED_TIME一天之内
                cTrucksUpdateQueryWrapper9.ge("HANDLED_TIME", now.truncatedTo(ChronoUnit.DAYS));
//            根据HANDLED_TIME查到最新的一条
                cTrucksUpdateQueryWrapper9.orderByDesc("HANDLED_TIME");
                cTrucksUpdateQueryWrapper9.last("limit 1");
                CTrucksUpdate cTrucksUpdate9 = cTrucksUpdateService.getOne(cTrucksUpdateQueryWrapper9);
                if (cTrucksUpdate9 != null) {
                    if (!cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆仍在队列中,由用户" + cTrucksUpdate9.getTrucksCheckinDriver() + "-" + cTrucksUpdate9.getTrucksCheckinDriverPhone() + "排队，请等待完成出厂后再申请排队");
                        return map1;
                    }
                } else {
                    if (cTrucks.getTrucksQueueStatus() != null && !cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆仍在队列中,请等待完成出厂后再申请排队");
                        return map1;
                    }
                }
            } catch (Exception e) {
                if (cTrucks.getTrucksQueueStatus() != null && !cTrucks.getTrucksQueueStatus().toString().equals("0")) {
                    map1.put("code", 1);
                    map1.put("msg", "该车辆仍在队列中,请等待完成出厂后再申请排队");
                    return map1;
                }
            }
        }
//        if (productsInfo.getPdtinfSpeSitelist() != null) {
////            当品种有装载点时cardinfTruckName不能为空
//            if (cardinfTruckName == null || cardinfTruckName.equals("")) {
//                map1.put("code", 1);
//                map1.put("msg", "请选择装卸货点!!!");
//                return map1;
//            }
//        }
        //        判断余额
//        queueHandlingBu.balanceIsEnough(plant, cardauthCardno);如果是false就提示余额不足
//        plant=DATA_FROM \ cardauthCardno=卡号 、cardinfTruckTypeValue=品种名称 、 cardinfTruckPwd=车号
//        if (!queueHandlingZxBu.balanceIsEnough(plant,cardinfCompanyCo,cardinfCompanyChiCo, cardinfTruckTypeValue, cardinfTruckPwd)) {
//            map1.put("code", 1);
//            map1.put("msg", "排队单位余额不足，请充值");
//            return map1;
//        }
//       邹县只判断下限余量
//        Map<String, Object> isLowerLimit = queueHandlingZxBu.isLowerLimit(plant, cardinfCompanyCo, cardinfCompanyChiCo, cardinfTruckTypeValue);
//        if (!isLowerLimit.get("ok").equals("0.0")) {
//            map1.put("code", 1);
//            if (!isLowerLimit.get("SubjectName").toString().equals("")) {
//                map1.put("msg", "排队单位的【" + isLowerLimit.get("SubjectName").toString() + "】账户余额不足装" + isLowerLimit.get("limit").toString() + "吨");
//            } else {
//                map1.put("msg", "排队单位未创建余额账户");
//            }
//            return map1;
//        }
//        邹县判断电厂公司余额下限  Map<String> getDianchangOrGongsiRemainMap = getDianchangOrGongsiRemain();
        Map<String, Object> isLowerLimit1 = getDianchangOrGongsiRemain(cCompanys.getId(), plant);
        if (Integer.parseInt(isLowerLimit1.get("code").toString()) == 1) {
            map1.put("code", 1);
            map1.put("msg", isLowerLimit1.get("msg"));
            return map1;
        }
//        判断是否还有计划
        boolean isPlan = queueHandlingZxBu.isPlanByPdtId(plant, cardinfCompanyCo, cardinfCompanyChiCo, cardinfTruckTypeValue, cTrucks6.getTrucksTruckno());
        if (!isPlan) {
            map1.put("code", 1);
            map1.put("msg", "无计划或计划已用完了");
            return map1;
        }
//        判断石膏渣是否有计划
//        这里还要排队石膏渣里有没有不需要排计划的品种
        if (getNoNeedPlan(productsInfo, plant)) {
//            只判断石膏和储备库炉渣的计划
            if ( productsInfo.getPdtinfClass().equals("2") || productsInfo.getId().equals("c9cf42874ddc446891ec936c5bf67386")) {
                String pdtId = productsInfo.getId();
                pdtId="7472d52542c54ce78917781471497559";
                //如果品种类型是石膏无论是一二期石膏还是三四期石膏，都按照石膏这一个品种来判断计划，和拿计划
                Map<String,Object> isPlan1 = queueHandlingZxBu.isPlan2(cCompanys1.getId(), pdtId);
                if(productsInfo.getPdtinfClass().equals("2"))
                {
                    //    直接查当天的石膏计划，石膏计划一天只有一个公司会有

                    isPlan1 = queueHandlingZxBu.isPlan4(now,cCompanys1.getId(), pdtId);
                    if (isPlan1.get("code").equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", "没有计划");
                        return map1;
                    }
                    TGypsumPlan tGypsumPlan = (TGypsumPlan) isPlan1.get("gypsumPlan");
                    cardinfCompanyId = tGypsumPlan.getCoId();
                }else{
                    isPlan1 = queueHandlingZxBu.isPlan2(cCompanys1.getId(), pdtId);
                    if (isPlan1.get("code").equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", "没有计划");
                        return map1;
                    }
                }
//
//    public Map<String,Object> isPlan3(String day, String pdtId) {


                TGypsumPlan tGypsumPlan = (TGypsumPlan) isPlan1.get("gypsumPlan");
                UpdateWrapper<CTrucks> cTrucksUpdateWrapper = new UpdateWrapper<>();
                cTrucksUpdateWrapper.eq("ID", cTrucks.getId());
                cTrucksUpdateWrapper.set("SUPPLY_CO_ID",tGypsumPlan.getSupplyCoId());
                cTrucksService.update(cTrucksUpdateWrapper);
            }

        }
//        =============================至此开始排队==================================================
        //        判断公司、电厂只要有一余额小于下限余额的就不给排队

//        查询管理员是否开启手机排队
        QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DIC_TYPE", "queue_phone");
        queryWrapper.eq("DIC_KEY", "queueControl");
        queryWrapper.eq("DATA_FROM", plant);
//        拿到结果
        SysDic sysDic = sysDicService.getOne(queryWrapper);
//        如果结果值为0，说明管理员开启了手机排队
        if (sysDic.getDicVal().equals("0")) {
//            找到ic卡的授权信息
            QueryWrapper<CTrucksUpdate> cTrucksUpdateQueryWrapper = new QueryWrapper<>();
            cTrucksUpdateQueryWrapper.eq("TRUCKS_TRUCKNO", cTrucks.getTrucksTruckno());
            cTrucksUpdateQueryWrapper.eq("TRUCKS_DELETED", 0);
            cTrucksUpdateQueryWrapper.eq("TRUCKS_NEW", 1);
//    HANDLED的值为字符串******，里面存在0，就说明还没处理
            cTrucksUpdateQueryWrapper.like("HANDLED", "0");
            CTrucksUpdate cTrucksUpdate1 = cTrucksUpdateService.getOne(cTrucksUpdateQueryWrapper);
            if (cTrucksUpdate1 != null) {
                String[] split = cTrucksUpdate1.getHandled().split("");
                for (String s : split) {
                    if (s.equals("0") || s.equals("1")) {
                        map1.put("code", 1);
                        map1.put("msg", "该车辆排队申请中，申请人:" + cTrucksUpdate1.getTrucksCheckinDriver() + "-" + cTrucksUpdate1.getTrucksCheckinDriverPhone() + "，请勿重复申请排队");
                        return map1;
                    }
                }
            }
            //        写入排队信息
            CTrucksUpdate cTrucksUpdate = new CTrucksUpdate();
            if (cTrucks != null) {
                cTrucksUpdate.setTrucksId(cTrucks.getTrucksId());
            }
            cTrucksUpdate.setTrucksTruckno(cTrucks.getTrucksTruckno());
            cTrucksUpdate.setTrucksCheckinCo(cardinfCompanyId);
            cTrucksUpdate.setTrucksCheckinPdt(productsInfo.getId());
            cTrucksUpdate.setTrucksCheckinPdtsn(productsInfo.getPdtinfSn());
            if (cardauthCardno != null) {
                cTrucksUpdate.setTrucksCheckinCardno(cardauthCardno);
            }
//                    cTrucksUpdate.setTrucksCheckinLoadsite(cardinfTruckName);
            cTrucksUpdate.setTrucksCheckinDriver(cardauthDriverUserName);
            cTrucksUpdate.setTrucksCheckinDriverPhone(cardauthDriverPhone);
            cTrucksUpdate.setTrucksQueueStatus(BigDecimal.valueOf(0));
            cTrucksUpdate.setHandled5Time(LocalDateTime.now());
            cTrucksUpdate.setHandledTime(LocalDateTime.now());
            cTrucksUpdate.setTrucksDeleted(0);
            cTrucksUpdate.setTrucksNew(1);
            cTrucksUpdate.setUpdateType(5);
//                                    cTrucksUpdate.setUpdateNew(0);
            cTrucksUpdate.setHandledResult(0);
            cTrucksUpdate.setHandled("22220222");
            cTrucksUpdate.setDataFrom(plant);
            cTrucksUpdateService.save(cTrucksUpdate);
            //      存完拿到id
            String id = cTrucksUpdate.getId();
            //                    往trucks表找到这个车号更新一下，往serialno也写入这个id
            QueryWrapper<CTrucks> cTrucksQueryWrapper2 = new QueryWrapper<>();
            cTrucksQueryWrapper2.eq("TRUCKS_TRUCKNO", cTrucks.getTrucksTruckno());
            cTrucksQueryWrapper2.eq("TRUCKS_DELETED", 0);
            CTrucks cTrucks2 = cTrucksService.getOne(cTrucksQueryWrapper2);
            if (cTrucks2 != null) {
                cTrucks2.setSerialNo(id);
                cTrucksService.updateById(cTrucks2);
            } else {
                map1.put("code", 1);
                map1.put("msg", "系统车库内没有该车号,请联系管理员添加");
                return map1;
            }
            //                    排队成功就将之前的记录置为0，也就是变成历史记录
            QueryWrapper<CTrucksUpdate> queryWrapper7 = new QueryWrapper<>();
            queryWrapper7.eq("ID", cTrucks.getId());
            queryWrapper7.eq("TRUCKS_NEW", 1);
            queryWrapper7.orderByDesc("HANDLED_TIME");
            List<CTrucksUpdate> cTrucksUpdates1 = cTrucksUpdateService.list(queryWrapper7);
            if (!cTrucksUpdates1.isEmpty()) {
                for (int i = 1; i < cTrucksUpdates1.size(); i++) {
                    CTrucksUpdate cTrucksUpdate2 = cTrucksUpdates1.get(i);
                    cTrucksUpdate2.setTrucksNew(0);
                    cTrucksUpdateService.updateById(cTrucksUpdate2);
                }
            }
//            车辆是否有vip排队特权
            if (cTrucks6 != null && cTrucks6.getTrucksQueueVipNums() > 0) {
                cTrucks.setTrucksQueueVipNums(cTrucks6.getTrucksQueueVipNums() - 1);
                cTrucks.setTrucksQueueVip(1);
            }
//            单位是否有vip排队特权
            if (cCompanys.getCpyQueueVip() == 1){
                cTrucks.setTrucksQueueVip(1);
            }
//                    排上队了就先改车子的状态为1
            cTrucks.setTrucksQueueStatus(BigDecimal.valueOf(1));
            cTrucks.setTrucksCheckinCo(cardinfCompanyId);
            cTrucks.setTrucksCheckinCardno(cardauthCardno);
            cTrucks.setTrucksCheckinPdt(productsInfo.getId());
            cTrucks.setTrucksCheckinTm(now);
            cTrucksService.updateById(cTrucks);
            //    直接叫号的品种，这些品种都是由装载点带回装载点编号，然后扣款时要根据装载点去找到是扣公司还是电厂的余额
            if (productsInfo.getId().equals("56260577b0ab4b5d9b84d9577fcac1d0")//大袋灰
                    || productsInfo.getId().equals("1dce738280ff4cfc946659990c8a05b6")//钢板仓粗灰
                    || productsInfo.getId().equals("025c559037d7462383b053630239ee49")//钢板仓原灰
//                    || productsInfo.getId().equals("8bebefb14fe3419ea957591b01774274")//一二期石膏
//                    || productsInfo.getId().equals("3365a55ec72e4e12b1ace84b2fdd9bec")//三四期石膏
//                    || productsInfo.getId().equals("7472d52542c54ce78917781471497559")//石膏
//                    || productsInfo.getId().equals("c9cf42874ddc446891ec936c5bf67386")//储备库炉渣
                    || productsInfo.getId().equals("af09ebfbecc04a4487f391f38567d8a8")//#6炉炉渣
                    || productsInfo.getId().equals("6225c8276b9e405a9bc61c1bc2d651cc")//#4炉炉渣
                    || productsInfo.getPdtinfClass().equals("4")//所有其他物资
                    || productsInfo.getId().equals("02fadd3e453840a5a19ee50d95a0092a")//转倒加湿灰
                    || productsInfo.getId().equals("f725ab248ca64e0ba3d3612eb0dab882")//应急加湿灰
                    || productsInfo.getId().equals("eaf0abcd61c04613aaa0d2387fee8fb6")//应急炉渣
                    || productsInfo.getId().equals("3cdf25f724764feea4d0d277667a2607")//转倒炉渣
                    || productsInfo.getId().equals("b9da511ff1dd4969a0e9ce0dbeeb91c9")//加湿灰
            ) {
                cTrucks.setTrucksCheckinLoadsite("");
                cTrucksService.updateById(cTrucks);
            }
//            cTrucks.setTrucksCheckinLoadsite(null);
//            cTrucks.setPriceType(null);
            UpdateWrapper<CTrucks> cTrucksUpdateWrapper = new UpdateWrapper<>();
            cTrucksUpdateWrapper.eq("ID", cTrucks.getId());
            cTrucksUpdateWrapper.set("TRUCKS_CHECKIN_LOADSITE",null);
            cTrucksUpdateWrapper.set("TRUCKS_CALLIN_TM",null);
            cTrucksUpdateWrapper.set("PRICE_TYPE", null);
            cTrucksUpdateWrapper.set("PRICE_ID", null);
            cTrucksUpdateWrapper.set("SPECIAL_PRICE", null);
            cTrucksService.update(cTrucksUpdateWrapper);
            //                    直接扣掉他的定价剩余情况
            TSpecialPrice priceDetail = getPriceDetail(productsInfo.getId(), cardinfCompanyId, String.valueOf(LocalDateTime.now()));
            if (priceDetail != null) {
                TSpecialPrice tSpecialPrice = new TSpecialPrice();
                tSpecialPrice.setId(priceDetail.getId());
                tSpecialPrice.setResidueNum(priceDetail.getResidueNum().subtract(BigDecimal.valueOf(1)));
                itSpecialPriceService.updateById(tSpecialPrice);
//                cTrucks.setSpecialPrice(tSpecialPrice.getPrice());
//                cTrucks.setPriceType(tSpecialPrice.getPriceType());
//                cTrucks.setPriceId(tSpecialPrice.getPriceTypeId());
//                UpdateWrapper<CTrucks> cTrucksUpdateWrapper1 = new UpdateWrapper<>();
//                cTrucksUpdateWrapper1.eq("ID", cTrucks.getId());
//                cTrucksUpdateWrapper1.set("PRICE_TYPE", tSpecialPrice.getPriceType());
//                cTrucksUpdateWrapper1.set("SPECIAL_PRICE", tSpecialPrice.getPrice());
//                cTrucksUpdateWrapper1.set("PRICE_ID", tSpecialPrice.getPriceTypeId());
//                cTrucksService.update(cTrucksUpdateWrapper1);
                cTrucks.setId(cTrucks.getId());
                cTrucks.setSpecialPrice(priceDetail.getPrice());
                cTrucks.setPriceType(priceDetail.getPriceType());
                cTrucks.setPriceId(priceDetail.getPriceTypeId());
                cTrucksService.updateById(cTrucks);
            }else {
//                cTrucks.setSpecialPrice(null);
//                cTrucks.setPriceType(null);
//                cTrucks.setPriceId(null);
                UpdateWrapper<CTrucks> cTrucksUpdateWrapper1 = new UpdateWrapper<>();
                cTrucksUpdateWrapper1.eq("ID", cTrucks.getId());
                cTrucksUpdateWrapper1.set("PRICE_TYPE", "市场价");
                cTrucksUpdateWrapper1.set("SPECIAL_PRICE", BigDecimal.valueOf(0));
                cTrucksUpdateWrapper1.set("PRICE_ID", "100db760390111ef987900ff8a757bed");
                cTrucksService.update(cTrucksUpdateWrapper1);
            }
            //            返回结果
            map1.put("id", id);
            map1.put("code", 0);
            map1.put("msg", "申请排队成功，请等待服务器响应");
            return map1;
        } else {
//            管理员关闭了手机排队往Map里写入错误信息
            map1.put("code", 1);
            map1.put("msg", "管理员关闭了手机排队功能");
            return map1;
        }
    }

    //    还得找粉煤灰的竞价信息、石膏的竞价信息、石膏渣的计划的价格数据
    public TSpecialPrice getPriceDetail(String pdtId, String coId, String checkinTm) {
        List<TSpecialPrice> list = fetchSpecialPrices(pdtId, coId, checkinTm);
        List<TSpecialPriceType> list1 = itSpecialPriceTypeService.list();

        // Filter out TSpecialPriceType where enableFlag is 0 before creating the map
        List<TSpecialPriceType> filteredList1 = list1.stream()
                .filter(priceType -> priceType.getEnableFlag() != 0)
                .collect(Collectors.toList());

        Map<String, TSpecialPriceType> priceTypeMap = filteredList1.stream()
                .collect(Collectors.toMap(TSpecialPriceType::getId, priceType -> priceType));

        // Filter TSpecialPrice objects based on the enableFlag of their associated TSpecialPriceType
        List<TSpecialPrice> filteredList = list.stream()
                .filter(sp -> priceTypeMap.containsKey(sp.getPriceTypeId()) && priceTypeMap.get(sp.getPriceTypeId()).getEnableFlag() != 0)
                .sorted(Comparator.comparing((TSpecialPrice sp) -> priceTypeMap.get(sp.getPriceTypeId()).getPriceSort())
                        .thenComparing(TSpecialPrice::getPrice))
                .collect(Collectors.toList());
        LinkedList<TSpecialPrice> linkedList = new LinkedList<>(filteredList);
        return linkedList.isEmpty() ? null : linkedList.get(0);
    }

    //拿到还有余量的定价数据
    private List<TSpecialPrice> fetchSpecialPrices(String pdtId, String coId, String checkinTm) {
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDT_ID", pdtId)
                .eq("CO_ID", coId)
                .le("START_TIME", checkinTm)
                .ge("END_TIME", checkinTm)
                .gt("RESIDUE_NUM", 0);
        return itSpecialPriceService.list(queryWrapper); // Assuming iTSpecialPriceService is an injected service
    }

    //    查询车辆黑名单情况
    public boolean getBlackList( String truckId, LocalDateTime checkinTm) {
        QueryWrapper<TTruckBlacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("END_TIME", checkinTm);
        queryWrapper.eq("TRUCK_ID", truckId);
        List<TTruckBlacklist> one = iTTruckBlacklistService.list(queryWrapper);
        return one.size() > 0;
    }

    //    查询这个车今天超时了几次了
    public Integer getOverTimeCount( String truckId, LocalDateTime checkinTm) {

        // Truncate checkinTm to the start of the day
        LocalDateTime startOfDay = checkinTm.withHour(0).withMinute(0).withSecond(0).withNano(0);

        QueryWrapper<TTrucksOvertime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TRUCK_ID", truckId);
        queryWrapper.ge("OVER_TIME", startOfDay);  // Greater than or equal to the start of the day
        List<TTrucksOvertime> list = iTTrucksOvertimeService.list(queryWrapper);

        return list.size();
    }

    //    新增车辆
    public Map<String, Object> addTruck(String trucksTruckno, String trucksTrailerno, String trucksType, Integer trucksLength, Integer trucksEmiss, Integer trucksAxles,
                                        Integer trucksRefTare, Integer trucksRefNet, String trucksMaster, String trucksIdentity, String trucksTell, String bindCoId, SysUser user, String plantId) throws Exception {
        // String plantId = plantId;
        CTrucks cTrucks = new CTrucks();
        if (trucksTruckno == null || trucksTruckno.isEmpty()) {
//            return SzResult.error("车牌号不能为空");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 1);
            map.put("msg", "车牌号不能为空");
            return map;
        }
        if (trucksType == null) {
//            return SzResult.error("车辆类型不能为空");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 1);
            map.put("msg", "车辆类型不能为空");
            return map;
        }
//如果trucksRefTare为Null或者为""或者为0那么trucksRefTare就是一个默认值
        if (trucksRefTare == null || trucksRefTare == 0) {
            QueryWrapper<CSysCfg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SYSCFG_ITEM_NAME", "TempTruckDefRefTare");
            queryWrapper.eq("DATA_FROM", plantId);
            CSysCfg one = cSysCfgService.getOne(queryWrapper);
            BigDecimal syscfgLongValue = one.getSyscfgLongValue();
            cTrucks.setTrucksRefTare(syscfgLongValue);
        } else {
            cTrucks.setTrucksRefTare(BigDecimal.valueOf(trucksRefTare));
        }
        if (trucksRefNet == null || trucksRefNet == 0) {
            QueryWrapper<CSysCfg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SYSCFG_ITEM_NAME", "TempTruckDefRefNet");
            queryWrapper.eq("DATA_FROM", plantId);
            CSysCfg one = cSysCfgService.getOne(queryWrapper);
            BigDecimal syscfgLongValue = one.getSyscfgLongValue();
            cTrucks.setTrucksRefNet(syscfgLongValue);
        } else {
            cTrucks.setTrucksRefNet(BigDecimal.valueOf(trucksRefNet));
        }


        QueryWrapper<CTrucks> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", trucksTruckno);
        queryWrapper.ne("TRUCKS_DELETED", 1);
        List<CTrucks> list = cTrucksService.list(queryWrapper);
        if (list.size() > 0) {
//        return SzResult.Error("车牌号已存在,请重新输入");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 1);
            map.put("msg", "车牌号已存在,请重新输入");
            return map;
        }

//        QueryWrapper<CTrucks> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("TRUCKS_TRAILERNO", trucksTrailerno);
//        queryWrapper1.eq("TRUCKS_DELETED", 0);
//        queryWrapper1.eq("DATA_FROM", plantId);
//        queryWrapper1.last("limit 1");
//        CTrucks one1 = iCTrucksService.getOne(queryWrapper1);
//        if (one1 != null) {
//            return SzResult.error("挂车号已存在,请重新输入");
//        }


        //trucksTruckno是由英文和数字组成
        if (!trucksTruckno.matches("^[\\u4e00-\\u9fa5A-Za-z0-9]+$")) {
//        return SzResult.error("车牌号只能由中文,英文和数字组成");
            Map<String, Object> map = new HashMap<>();
            map.put("code", 1);
            map.put("msg", "车牌号只能由中文,英文和数字组成");
            return map;
        }
//    车号包括汽车号与新能源车号，可能存在不只是7的情况
//    if (trucksTruckno.length() != 7) {
////        return SzResult.error("车牌号只能是7位");
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", 1);
//        map.put("msg", "车牌号只能是7位");
//        return map;
//    }


        cTrucks.setTrucksTruckno(trucksTruckno);
        if (trucksTrailerno != null && !trucksTrailerno.isEmpty()) {
            cTrucks.setTrucksTrailerno(trucksTrailerno);
        }
        cTrucks.setTrucksType(BigDecimal.valueOf(Long.parseLong(trucksType)));

        if (trucksLength != null) {
            cTrucks.setTrucksLength(BigDecimal.valueOf(trucksLength));
        }
        if (trucksEmiss != null) {
            cTrucks.setTrucksEmiss(BigDecimal.valueOf(trucksEmiss));
        }
        if (trucksAxles != null) {
            cTrucks.setTrucksAxles(BigDecimal.valueOf(trucksAxles));
        }

        if (trucksMaster != null && !trucksMaster.isEmpty()) {
            cTrucks.setTrucksMaster(trucksMaster);
        }
        if (trucksIdentity != null && !trucksIdentity.isEmpty()) {
            cTrucks.setTrucksIdentity(trucksIdentity);
        }
        if (trucksTell != null && !trucksTell.isEmpty()) {
            cTrucks.setTrucksTell(trucksTell);
        }
        if (bindCoId != null && !bindCoId.equals("")) {
            cTrucks.setBindCoId(bindCoId);
        }
        cTrucks.setTrucksDeleted(0);
        cTrucks.setTrucksInfoApproved(1);
        //形成时间戳
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        format = format.replace("-", "").replace(" ", "").replace(":", "");
        cTrucks.setId(format);
        cTrucks.setTrucksId(new BigDecimal(format));
        cTrucks.setTrucksEntered(0);//0为不允许,1为允许
//        SysUser user1 = user;
        if (user != null && user.getTrueName() != null) {
            cTrucks.setTrucksRegMan(user.getTrueName());
        }
        //判断标签1，标签2，标签3是否存在，有一个存在即可
//        if (cTrucks.getDownedID16() != null || cTrucks.getDownedID17() != null || cTrucks.getDownedID18() != null
//                || cTrucks.getDownedID19() != null || cTrucks.getDownedID20() != null) {
//            if ()
//            cTrucks.setTrucksFixMan(user.getTrueName());
//        }
        cTrucks.setDataFrom(plantId);
        cTrucks.setTrucksRefTareInited(0);
        cTrucks.setTrucksMustQueue(0);
        cTrucks.setTrucksIdentyQueue(0);
        cTrucks.setTrucksIdentyLoad(0);
//    新加的车辆信息直接就给批准了
        cTrucks.setTrucksInfoApproved(1);
        cTrucks.setDownedID1(0);
        cTrucks.setTrucksDeleted(0);
        cTrucks.setDataFrom(plantId);
        cTrucksService.save(cTrucks);
        if (user != null) {
            sysLogBu.logRecord("新增车辆信息", user.getTrueName(), "新增了车牌号为" + trucksTruckno + "的临时车辆信息", plantId);
        }else{
            sysLogBu.logRecord("新增车辆信息","排队机", "新增了车牌号为" + trucksTruckno + "的临时车辆信息", plantId);
        }
//    return SzResult.Success();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "新增临时车号成功");
        return map;
    }

    ////        这里还要排队石膏渣里有没有不需要排计划的品种，true需要排计划
    public boolean getNoNeedPlan(CProductsInfo productsInfo, String plantId) {
//        先判断储备库炉渣是否要排计划c9cf42874ddc446891ec936c5bf67386，储备库炉渣是有计划开关的
        if (productsInfo.getPdtinfPdt().equals("储备库炉渣") || productsInfo.getId().equals("c9cf42874ddc446891ec936c5bf67386")) {
            QueryWrapper<SysDic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DIC_KEY", "queueControl_chubkuluzha_plan");
            queryWrapper.eq("DATA_FROM", plantId);
            SysDic one = sysDicService.getOne(queryWrapper);
            return one.getDicVal().equals("1");
        }
//            应急炉渣不需要排计划
        if (productsInfo.getPdtinfPdt().equals("应急炉渣")) {
            return false;
        }
        //            转倒炉渣不需要排计划
        if (productsInfo.getPdtinfPdt().equals("转倒炉渣")) {
            return false;
        }
        return true;
    }

    //    判断可以使用临时车号的品种
//
////       炉渣
    public boolean getCanUseTempTruckNo(CProductsInfo productsInfo, String plantId) {
//        大袋灰、加湿灰可以排临时车
        if (productsInfo.getPdtinfPdt().contains("大袋灰") || productsInfo.getPdtinfPdt().contains("加湿灰")) {
            return false;
        }
//炉渣可以使用临时车排队
        if (productsInfo.getPdtinfPdt().contains("炉渣")) {
            return true;
        }
        return false;
    }

    //        判断公司、电厂只要有一余额小于下限余额的就不给排队getDianchangOrGongsiRemain

    public Map<String, Object> getDianchangOrGongsiRemain(String coId, String plantId) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "余额正常");
//        排队单位
        QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", coId);
        queryWrapper.eq("DATA_FROM", plantId);
        CCompanys one1 = cCompanysService.getOne(queryWrapper);
//        收款单位（电厂）
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("CPY_CO", "电厂");
        queryWrapper2.eq("CPY_DELETED", 0);
        queryWrapper2.eq("DATA_FROM", plantId);
        CCompanys dianchang = cCompanysService.getOne(queryWrapper2);
//        查询他的电厂的余额
        QueryWrapper<COrderDetail> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("ORDETAIL_CO", one1.getCpyCo());
        queryWrapper3.eq("ORDETAIL_CHICO", one1.getCpyChico());
        queryWrapper3.eq("ORDETAIL_SUB_ID", dianchang.getId());
        queryWrapper3.eq("ORDETAIL_DELETED", 0);
        queryWrapper3.eq("DATA_FROM", plantId);
        COrderDetail cOrderDetail = iCOrderDetailService.getOne(queryWrapper3);
        if (cOrderDetail == null) {
            map.put("code", 1);
            map.put("msg", "电厂账户不存在");
            return map;
        }
//查询电厂的下限额度
        QueryWrapper<SysDic> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("DIC_KEY", "queueControl_dianchang_remain");
        queryWrapper4.eq("DATA_FROM", plantId);
        SysDic one = sysDicService.getOne(queryWrapper4);
        BigDecimal syscfgLongValue = BigDecimal.valueOf(Long.parseLong(one.getDicVal()));
        if (cOrderDetail.getOrdetailRemainNum().compareTo(syscfgLongValue) < 0) {
            map.put("code", 1);
            map.put("msg", "电厂余额小于" + syscfgLongValue);
            return map;
        }
//        收款单位（公司）
        QueryWrapper<CCompanys> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("CPY_CO", "公司");
        queryWrapper5.eq("CPY_DELETED", 0);
        queryWrapper5.eq("DATA_FROM", plantId);
        CCompanys gongsi = cCompanysService.getOne(queryWrapper5);
//        查询他的电厂的余额
        QueryWrapper<COrderDetail> queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.eq("ORDETAIL_CO", one1.getCpyCo());
        queryWrapper6.eq("ORDETAIL_CHICO", one1.getCpyChico());
        queryWrapper6.eq("ORDETAIL_SUB_ID", gongsi.getId());
        queryWrapper6.eq("ORDETAIL_DELETED", 0);
        queryWrapper6.eq("DATA_FROM", plantId);
        COrderDetail cOrderDetail2 = iCOrderDetailService.getOne(queryWrapper6);
        if (cOrderDetail2 == null) {
            map.put("code", 1);
            map.put("msg", "公司账户不存在");
            return map;
        }
        //查询公司的下限额度
        QueryWrapper<SysDic> queryWrapper7 = new QueryWrapper<>();
        queryWrapper7.eq("DIC_KEY", "queueControl_gongsi_remain");
        queryWrapper7.eq("DATA_FROM", plantId);
        SysDic tow = sysDicService.getOne(queryWrapper7);
        BigDecimal syscfgLongValue2 = BigDecimal.valueOf(Long.parseLong(tow.getDicVal()));
        if (cOrderDetail2.getOrdetailRemainNum().compareTo(syscfgLongValue2) < 0) {
            map.put("code", 1);
            map.put("msg", "公司余额小于" + syscfgLongValue2);
            return map;
        }
        return map;
    }

    //    一二期石膏、三四期石膏这两品种排队要判断有没有打包销售的量
    public boolean ifPackageSell(String plant, String coId, String pdtId, LocalDateTime checkinTm) {
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CO_ID", coId);
        queryWrapper.eq("PDT_ID", pdtId);
        queryWrapper.eq("DATA_FROM", plant);
        queryWrapper.le("START_TIME", checkinTm);
        queryWrapper.ge("END_TIME", checkinTm);
//        打包销售的typeId
        queryWrapper.eq("PRICE_TYPE_ID", "0705df3110c911ef823f00ff8a757bed");
//        大于0就是还有量
        queryWrapper.gt("RESIDUE_NUM",0);
        queryWrapper.ne("DEL_FLAG",1);
        TSpecialPrice one = itSpecialPriceService.getOne(queryWrapper);
        if (one != null) {
            return false;
        } else {
            return true;
        }
    }

    public void updateTruckQueueNo() {
        QueryWrapper<CTrucks> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("TRUCKS_QUEUE_STATUS", 0);
        queryWrapper.ne("TRUCKS_DELETED", 1);
        queryWrapper.isNotNull("TRUCKS_CHECKIN_PDT");
        queryWrapper.isNotNull("TRUCKS_CHECKIN_TM");
        List<CTrucks> cTrucks = cTrucksService.list(queryWrapper);
        // 使用 LinkedHashMap 来保持分组的插入顺序
        Map<String, List<CTrucks>> groupedAndSorted = cTrucks.stream()
                .collect(Collectors.groupingBy(
                        CTrucks::getTrucksCheckinPdt,
                        LinkedHashMap::new,
                        Collectors.toList()));
        // 遍历每个分组，并在每个组内按 trucksCheckinTM 排序
        groupedAndSorted.forEach((pdt, trucks) -> {
            // 先将卡车按照是否 VIP 分类
            List<CTrucks> vipTrucks = trucks.stream()
                    .filter(truck -> truck.getTrucksQueueVip() == 1)
//                    100db760390111ef987900ff8a757bed为市场价id
                    .sorted(Comparator.comparing((CTrucks truck) -> {
                                String priceId = truck.getPriceId();
                                // 如果 priceId 为空或者为空字符串，则返回 1，表示较低的优先级
                                if (priceId == null || priceId.isEmpty()) {
                                    return 1;
                                }
                                // 如果 priceId 等于特定市场价 ID，则返回 0，表示较高的优先级
                                return priceId.equals("100db760390111ef987900ff8a757bed") ? 0 : 1;
                            })
                            .thenComparing(Comparator.comparing(CTrucks::getSpecialPrice, Comparator.nullsFirst(Comparator.reverseOrder())))
                            .thenComparing(CTrucks::getTrucksCheckinTm))
                    .collect(Collectors.toList());

            List<CTrucks> nonVipTrucks = trucks.stream()
                    .filter(truck -> truck.getTrucksQueueVip() != 1)
                    .sorted(Comparator.comparing((CTrucks truck) -> {
                                String priceId = truck.getPriceId();
                                // 如果 priceId 为空或者为空字符串，则返回 1，表示较低的优先级
                                if (priceId == null || priceId.isEmpty()) {
                                    return 1;
                                }
                                // 如果 priceId 等于特定市场价 ID，则返回 0，表示较高的优先级
                                return priceId.equals("100db760390111ef987900ff8a757bed") ? 0 : 1;
                            })
                            .thenComparing(Comparator.comparing(CTrucks::getSpecialPrice, Comparator.nullsFirst(Comparator.reverseOrder())))
                            .thenComparing(CTrucks::getTrucksCheckinTm))
                    .collect(Collectors.toList());

            // 合并两个列表
            List<CTrucks> allTrucks = Stream.concat(vipTrucks.stream(), nonVipTrucks.stream())
                    .collect(Collectors.toList());
            // 给每个卡车分配一个检查编号
            int queueNo = 1;
            for (CTrucks truck : allTrucks) {
                truck.setTrucksCheckinNo(BigDecimal.valueOf(queueNo++));
            }

            // 使用 MyBatis Plus 的批量更新方法
            cTrucksService.updateBatchById(allTrucks);
        });
    }

//    85、石膏手动排队的时候，自动查找当天的计划客户，若是一二期石膏或者三四期石膏，那么就是找到计划单位的公司和电厂，然后使用打包销售的单位信息进行排队
    public void getGypPlanCustomer(String plantId, String coId) {


    }

    //拿到一个临时卡号(1-100号卡）
    public String getTempTruckIc(String plantId) {
        // 创建查询条件
        QueryWrapper<CIcCardsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_FROM", plantId);

        // 创建一个包含 "00001" 到 "00100" 的字符串列表
        List<String> idList = IntStream.rangeClosed(1, 100)
                .mapToObj(i -> String.format("%05d", i))
                .collect(Collectors.toList());

        // 添加其他查询条件
        queryWrapper.in("CARDINF_CARDNO", idList);
        queryWrapper.eq("CARDINF_DELETED", 0);
        queryWrapper.eq("CARDINF_REPORT_LOST", 0);
        queryWrapper.eq("CARDINF_CUR_VALID", 1);

        // 获取符合条件的卡片列表
        List<CIcCardsInfo> list = cIcCardsInfoService.list(queryWrapper);

        // 过滤掉被占用的卡片
        List<CIcCardsInfo> availableCards = new ArrayList<>();
        for (CIcCardsInfo card : list) {
            // 检查卡片是否被占用
            QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
            trucksQueryWrapper.eq("TRUCKS_CHECKIN_CARDNO", card.getCardinfCardno());
            trucksQueryWrapper.ne("TRUCKS_QUEUE_STATUS", 0);
            trucksQueryWrapper.eq("TRUCKS_DELETED", "0");

            List<CTrucks> cTrucks = cTrucksService.list(trucksQueryWrapper);
            if (cTrucks.size() == 0) {
                // 如果没有找到对应的卡车记录，说明该卡片未被占用
                availableCards.add(card);
            }
        }

        // 返回第一个未被占用的卡片号
        if (!availableCards.isEmpty()) {
            return availableCards.get(0).getCardinfCardno();
        } else {
            return null;
        }
    }


    //拿到一个临时加湿灰卡
    public String getJiashihuiTempTruckIc(String plantId, boolean useCard) {
        // 创建查询条件
        QueryWrapper<CIcCardsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_FROM", plantId)
                .eq("CARDINF_DELETED", 0)
                .eq("CARDINF_TYPE", "附卡(绑定密码)")
                .eq("CARDINF_PREFER_PDT", "加湿灰")
                .eq("CARDINF_REPORT_LOST", 0)
                .eq("CARDINF_CUR_VALID", 1);

        // 获取符合条件的卡片列表
        List<CIcCardsInfo> list = cIcCardsInfoService.list(queryWrapper);

        // 过滤掉被占用的卡片
        List<CIcCardsInfo> availableCards = list.stream()
                .filter(card -> {
                    QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
                    trucksQueryWrapper.eq("TRUCKS_CHECKIN_CARDNO", card.getCardinfCardno())
                            .ne("TRUCKS_QUEUE_STATUS", 0)
                            .eq("TRUCKS_DELETED", "0");
                    return cTrucksService.list(trucksQueryWrapper).isEmpty();
                })
                .collect(Collectors.toList());

        // 使用CardAssignmentManager获取下一个可用卡号
        return CardAssignmentManager.getNextAvailableCardNo(availableCards, useCard);
    }

    //拿到一个临时加湿灰卡
    public String getJiashihuiTempTruckIc2(String plantId, boolean useCard) {
        // 创建查询条件
        QueryWrapper<CIcCardsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_FROM", plantId)
                .eq("CARDINF_DELETED", 0)
                .eq("CARDINF_TYPE", "附卡(绑定密码)")
                .eq("CARDINF_PREFER_PDT", "应急加湿灰")
                .eq("CARDINF_REPORT_LOST", 0)
                .eq("CARDINF_CUR_VALID", 1);

        // 获取符合条件的卡片列表
        List<CIcCardsInfo> list = cIcCardsInfoService.list(queryWrapper);

        // 过滤掉被占用的卡片
        List<CIcCardsInfo> availableCards = list.stream()
                .filter(card -> {
                    QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
                    trucksQueryWrapper.eq("TRUCKS_CHECKIN_CARDNO", card.getCardinfCardno())
                            .ne("TRUCKS_QUEUE_STATUS", 0)
                            .eq("TRUCKS_DELETED", "0");
                    return cTrucksService.list(trucksQueryWrapper).isEmpty();
                })
                .collect(Collectors.toList());

        // 使用CardAssignmentManager获取下一个可用卡号
        return CardAssignmentManager.getNextAvailableCardNo2(availableCards, useCard);
    }

    //拿到一个临时加湿灰卡
    public String getJiashihuiTempTruckIc3(String plantId, boolean useCard) {
        // 创建查询条件
        QueryWrapper<CIcCardsInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_FROM", plantId)
                .eq("CARDINF_DELETED", 0)
                .eq("CARDINF_TYPE", "附卡(绑定密码)")
                .eq("CARDINF_PREFER_PDT", "转倒加湿灰")
                .eq("CARDINF_REPORT_LOST", 0)
                .eq("CARDINF_CUR_VALID", 1);

        // 获取符合条件的卡片列表
        List<CIcCardsInfo> list = cIcCardsInfoService.list(queryWrapper);

        // 过滤掉被占用的卡片
        List<CIcCardsInfo> availableCards = list.stream()
                .filter(card -> {
                    QueryWrapper<CTrucks> trucksQueryWrapper = new QueryWrapper<>();
                    trucksQueryWrapper.eq("TRUCKS_CHECKIN_CARDNO", card.getCardinfCardno())
                            .ne("TRUCKS_QUEUE_STATUS", 0)
                            .eq("TRUCKS_DELETED", "0");
                    return cTrucksService.list(trucksQueryWrapper).isEmpty();
                })
                .collect(Collectors.toList());

        // 使用CardAssignmentManager获取下一个可用卡号
        return CardAssignmentManager.getNextAvailableCardNo3(availableCards, useCard);
    }
}
